<template lang="html">
    <div class="upload-components">
        <input type="file" style="display: none;" @change="toUpload($event)" ref="uploadInput" />
        <div class="show-upload" @click="uploadFile" v-if="!resPath">
            <i class="iconfont icon-add i-font" ></i>
        </div>
        <div class="image-show" v-if="resPath">
            <img :src="resPath" @click="previewImage($event)" alt="">
        </div>
    </div>
</template>

<script>
import ImagePreview from 'vant/lib/image-preview'
export default {
    data(){
        return {
            resPath: ''
        }
    },
    methods: {
        uploadFile(){
            this.$refs.uploadInput.click()
        },
        toUpload(e){
            let formData = new FormData();
            // let token = localStorage.getItem('token')
            // formData.append('token', token)
            formData.append('UploadForm[imageFile]', e.target.files[0])
            this.$api.post('/other/upload', formData, false).then(res => {
                this.resPath = process.env.BASE_URL + '/' + res
                this.$emit('uploadOk', res)
            }).catch(e => {
                console.log(e.message);
            })
        },
        previewImage(e){
            ImagePreview([event.target.src]);
        }
    }
}
</script>

<style lang="scss" scoped>
    .upload-components{
        .show-upload{
            background: #ff9;
            width: .8rem;
            height: .8rem;
            background-color: #fafafa;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            border-radius: 4px;
            border: 1px dashed #d9d9d9;
            transition: all 0.3s;
            .i-font{
                font-size: .22rem;
                color: #999;
            }
        }
        .show-upload:hover{
            border-color: #1890ff;
        }
        .image-show{
            img{
                width: .8rem;
                height: .8rem;
                object-fit: cover;
            }
        }
    }
</style>
